package servlet;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class GetSetCookie {

    public static void set(HttpServletResponse response,String username,String password) {
        Cookie cookie = new Cookie("login_staff", username + "#" + password);
        cookie.setMaxAge(30);
        response.addCookie(cookie);
    }

    private static Map<String, String> getLoginParams(Cookie cookie) {
        Map<String, String> map = new HashMap<>();
        //分割，取得密码与用户名
        String[] params = cookie.getValue().split("#");
        String loginName = params[0];
        String loginPassword = params[1];
        //存入集合
        map.put("username", loginName);
        map.put("password", loginPassword);
        //
        return map;
    }

    public static Map<String, String> get(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        //取得cookie
        Cookie[] cookies = request.getCookies();
        //判断cookie
        if (cookies == null) {
            return null;
        }
        //
        for (Cookie cookie: cookies) {
            if ("login_staff".equals(cookie.getName())) {
                //取得
                map = getLoginParams(cookie);
            }
        }
        //
        return map;
    }

    public static void delete(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
    }
}
